package com.mmall.service.impl;

import com.mmall.common.Const;
import com.mmall.common.ServerResponse;
import com.mmall.common.TokenCache;
import com.mmall.dao.UserMapper;
import com.mmall.pojo.User;
import com.mmall.service.IUserService;
import com.mmall.util.MD5Util;

import org.apache.commons.lang3.StringUtils;

import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.stereotype.Service;

import java.util.UUID;

@Service("iUserService")
public class IUserServiceImpl implements IUserService {
    @Autowired
    private UserMapper userMapper;
    @Override
    public ServerResponse<User> login(String username,String password) {
        int countUser = userMapper.checkUsername(username);
        if(countUser==0){
            return ServerResponse.createByErrorMessage("用户名不存在");
        }

        //md5加密
        String md5Password=MD5Util.MD5EncodeUtf8(password);
        User user = userMapper.selectLogin(username, password);
        if(user==null){
            return ServerResponse.createByErrorMessage("密码错误");
        }

        user.setPassword(StringUtils.EMPTY);
        return ServerResponse.createBySuccess("登录成功",user);
    }

    @Override
    public ServerResponse<String> register(User user) {
        ServerResponse<String> checkValid = this.checkValid(user.getUsername(), Const.USERNAME);
        if(!checkValid.isSuccess()){
            return checkValid;
        }
        ServerResponse<String> checkValid1 = this.checkValid(user.getEmail(), Const.EMAIL);
        if(!checkValid1.isSuccess()){
            return checkValid1;
        }
        user.setRole(Const.Role.ROLE_CUSTOMER);
        user.setPassword(MD5Util.MD5EncodeUtf8(user.getPassword()));
        int count = userMapper.insert(user);
        if(count==0){
            return ServerResponse.createByErrorMessage("注册失败");
        }
        return ServerResponse.createBySuccessMessage("注册成功");
    }
    //判断注册用户名或邮箱是否可用
    public ServerResponse<String> checkValid(String str,String type){
        if(StringUtils.isBlank(type)){
            //开始校验
            if(Const.USERNAME.equals(type)){
                int checkResult = userMapper.checkUsername(str);
                if (checkResult!=0){
                    return ServerResponse.createByErrorMessage("用户名已存在");
                }
            }
            if(Const.EMAIL.equals(type)){
                int checkEmail = userMapper.checkEmail(str);
                if (checkEmail!=0){
                    return ServerResponse.createByErrorMessage("email已存在");
                }
            }
        }else {
            return ServerResponse.createByErrorMessage("参数错误");
        }
        return ServerResponse.createBySuccessMessage("校验成功");
    }

    @Override
    public ServerResponse selectQuestion(String username) {
        ServerResponse<String> response = this.checkValid(username, Const.USERNAME);
        if(response==null){
            return ServerResponse.createByErrorMessage("用户名不存在");
        }
        String question = userMapper.selectQuestionByUsername(username);
        if(StringUtils.isNotBlank(question)){
            return ServerResponse.createByErrorMessage(question);
        }
        return ServerResponse.createByErrorMessage("用户未设置找回密码问题");
    }

    @Override
    public ServerResponse<String> checkAnswer(String username, String question, String answer) {
        int checkAnswer = userMapper.checkAnswer(username, question, answer);
        if(checkAnswer>0){
            String forgetToken = UUID.randomUUID().toString();
            TokenCache.setKey(TokenCache.TOKEN_PREFIX+username,forgetToken);
            return ServerResponse.createBySuccessMessage(forgetToken);
        }
        return ServerResponse.createByErrorMessage("问题答案错误");
    }

    @Override
    public ServerResponse<String> forgetResetPassword(String username, String passwordNew, String forgetToken) {
        if(StringUtils.isBlank(forgetToken)){
            return ServerResponse.createByErrorMessage("参数错误,token需要传递");
        }

        ServerResponse<String> checkValid = this.checkValid(username, Const.USERNAME);
        if(!checkValid.isSuccess()){
            return ServerResponse.createByErrorMessage("用户不存在");
        }

        String token = TokenCache.getKey(TokenCache.TOKEN_PREFIX + username);
        if (StringUtils.isBlank(token)){
            return ServerResponse.createByErrorMessage("token无效或者过期");
        }

        if(StringUtils.equals(forgetToken,token)){
            int result = userMapper.updatePasswordByUsername(username, passwordNew);
            if(result>0){
                return ServerResponse.createBySuccessMessage("密码更新成功");
            }else {
                return ServerResponse.createByErrorMessage("token错误,请重新获取重置密码的token");
            }
        }
        return ServerResponse.createByErrorMessage("密码更新失败");
    }

    @Override
    public ServerResponse<String> resetPassword(String passwordOld, String passwordNew,User user) {
        int checkPassword = userMapper.checkPassword(passwordOld, user.getId());
        if(checkPassword==0){
            return ServerResponse.createByErrorMessage("旧密码错误");
        }
        user.setPassword(MD5Util.MD5EncodeUtf8(passwordNew));
        int update = userMapper.updateByPrimaryKey(user);
        if(update>0){
            return ServerResponse.createBySuccessMessage("密码更新成功");
        }else {
            return ServerResponse.createByErrorMessage("密码更新失败");
        }
    }

    @Override
    public ServerResponse<User> updateInformation(User user) {
        int checkEmailByUserId = userMapper.checkEmailByUserId(user.getEmail(), user.getId());
        if(checkEmailByUserId>0){
            return ServerResponse.createByErrorMessage("email已存在，请更换");
        }
        User updateUser=new User();
        updateUser.setEmail(user.getEmail());
        updateUser.setId(user.getId());
        updateUser.setQuestion(user.getQuestion());
        updateUser.setAnswer(user.getAnswer());

        int update = userMapper.updateByPrimaryKeySelective(updateUser);
        if(update>0){
            return ServerResponse.createBySuccess("更新个人信息成功",updateUser);
        }
        return ServerResponse.createByErrorMessage("更新个人信息失败");
    }

    @Override
    public ServerResponse<User> getInformation(Integer id) {
        User user = userMapper.selectByPrimaryKey(id);
        if(user==null){
            return ServerResponse.createByErrorMessage("找不到当前用户");
        }
        user.setPassword(StringUtils.EMPTY);

        return ServerResponse.createBySuccess(user);
    }


}
